 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package cn.shun.controller;

 import cn.hutool.jwt.JWT;
 import cn.hutool.jwt.JWTUtil;
 import cn.shun.dao.UserDao;
 import cn.shun.model.UserLoginInfo;
 import cn.shun.exception.BizException;
 import cn.shun.pojo.User;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.bind.annotation.*;

 import java.util.HashMap;
 import java.util.Map;

 /**
  * <p>Project: sboot_2023-cn.shun.controller-UserController
  * <p>Powered by yishun On 2023-04-13 21:15:58
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 @RestController
 @RequestMapping("/api/user")
 @Slf4j

 public class UserController {
     @Autowired
     private UserDao userDao;
     @Value("${token.Key}")
     private String tokenKey;


     @GetMapping
     public Object list() {
         return userDao.queryPage();
     }

     @GetMapping("/{id}")
     public User one(@PathVariable Integer id) {
         return userDao.selectById(id);
     }

     @PostMapping("/register")
     public Integer register(@RequestBody User user) {
         int rouNum = userDao.insert(user);
         if (rouNum == 1) {
             return rouNum;
         }
         throw new BizException(1002, "注册失败");
     }

     @PostMapping("/login")
     public String login(@RequestBody UserLoginInfo userLoginInfo) {
         User user = userDao.selectOne(userLoginInfo);
         if (user != null) {
             Map<String, Object> map = new HashMap<>();
             map.put("id", user.getId());
             String tel = user.getTel().substring(0, 3) + "****" + user.getTel().substring(7);
             map.put("tel", tel);
             //设置过期时间
             map.put(JWT.EXPIRES_AT, System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000);
             String token = JWTUtil.createToken(map, tokenKey.getBytes());
             return token;
         }
         throw new BizException(1001, "用户名或密码错误");
     }

     @DeleteMapping
     public Integer delete(@RequestParam Integer id) {
         return userDao.deleteById(id);
     }

     @PutMapping
     public Integer update(@RequestBody User user) {
         return userDao.updateById(user);
     }


 }
